package com.lsl.endworkvol.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.lsl.endworkvol.entity.Activity;
import com.lsl.endworkvol.entity.SignUpNote;
import com.lsl.endworkvol.entity.Volunteer;
import com.lsl.endworkvol.service.ActivityScoreService;
import com.lsl.endworkvol.service.ActivityService;
import com.lsl.endworkvol.service.ActivitySignUpService;
import com.lsl.endworkvol.service.VolunteerService;

@Controller
public class ActivityNoteController {

    @Autowired
    private ActivitySignUpService activitySignUpService;

    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityScoreService activityScoreService;

    @RequestMapping(path = "/volunteer/warning/you_had_signed_up_this_activity", method = RequestMethod.GET)
    public ModelAndView toWarnYouHadSignedUpThisActivityPage(ModelAndView modelAndView) {
        modelAndView.setViewName("volunteer/warn_pages/you_had_signed_up_this_activity");
        return modelAndView;
    }

    @GetMapping(value = "/leader/volunteer_score_page/{note_id}")
    public ModelAndView toVolunteerGradePage(@PathVariable(value = "note_id") String noteId , ModelAndView modelAndView) {
        modelAndView.setViewName("leader/volunteer_grade");
        modelAndView.addObject("noteId", noteId);
        return modelAndView;
    }
    
    @RequestMapping(value = "/volunteer/activity_signup/{activityid}/{userid}", method = RequestMethod.GET)
    public String signupActivity(
        @PathVariable(value = "activityid") String activityid,
        @PathVariable(value = "userid") String userid, 
        HttpServletResponse response
    ) {
        SignUpNote note = new SignUpNote();
        note.setActivityId(Integer.parseInt(activityid));
        note.setVolunteerId(Integer.parseInt(userid));
        if(!activitySignUpService.getNotes(() -> { return note; }).isEmpty()) {
            return "redirect:/volunteer/warning/you_had_signed_up_this_activity";
        }
        boolean flag = activitySignUpService.signupActivity(() -> {
            note.setScore(null);
            note.setCheckOutFlag(0);
            return note;
        });
        if(flag) {
            return "redirect:/volunteer/activities_list_page";
        } else {
            return "redirect:/volunteer/warn_pages/you_had_signed_up_this_activity.jsp";
        }
    }

    @GetMapping(value = "/volunteer/activity_exit/{id}")
    public String exitActivity(@PathVariable(value = "id") String id, ModelAndView modelAndView) {
        boolean flag = activitySignUpService.exitActivity(id);
        if(flag) {
            return "redirect:/volunteer/message/exit_activity_success";
        } else {
            return "redirect:/volunteer/warning/exit_activity_failed";
        }
    }

    @GetMapping(value = "/volunteer/activity_checkout/{id}")
    public String CheckOutActivityByVolunteer(@PathVariable(value = "id") String id, ModelAndView modelAndView) {
        boolean flag = activitySignUpService.checkOutActivity(id);
        if (flag) {
            return "redirect:/volunteer/message/checkout_success";
        } else {
            return "redirect:/volunteer/warning/checkout_failed";
        }
    }

    @RequestMapping(path = "/leader/activity_select", method = RequestMethod.POST)
    public ModelAndView selectActivity(@RequestParam(value = "activity_id") String id, ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("leader/activities_checkout_list");
        List<Activity> activitiesList = activityService.getActivities(
            request.getSession().getAttribute("userid").toString()
        );
        List<Volunteer> volunteersList = new ArrayList<>();
        List<String> checkOutStatusList = new ArrayList<>();
        List<Integer> notesIdList = new ArrayList<>(); 
        List<SignUpNote> notesList = activitySignUpService.getNotes(() -> {
            SignUpNote note = new SignUpNote();
            note.setActivityId(Integer.parseInt(id));
            return note;
        });
        for (SignUpNote note : notesList) {
            volunteersList.add((Volunteer)volunteerService.getUser(note.getVolunteerId()));
            checkOutStatusList.add(note.getCheckOutFlag() == 1 ? "已签到" : "未签到");
            notesIdList.add(note.getId());
        }
        modelAndView.addObject("selectedActivityId", id);
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("userList", volunteersList);
        modelAndView.addObject("notesCheckOutStatusList", checkOutStatusList);
        modelAndView.addObject("notesIdList", notesIdList);
        return modelAndView;
    }

    @RequestMapping(path = "/leader/activity_select_for_grade", method = RequestMethod.POST)
    public ModelAndView selectActivityForGrade(@RequestParam(value = "activity_id") String id, ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("leader/activities_grade");
        List<Activity> allactivitiesList = activityService.getActivities(
            request.getSession().getAttribute("userid").toString()
        );
        List<Volunteer> volunteersList = new ArrayList<>();
        List<String> checkOutStatusList = new ArrayList<>();
        List<Integer> notesIdList = new ArrayList<>(); 
        List<Integer> notesGradeList = new ArrayList<>();
        List<Activity> activitiesList = new ArrayList<>();
        Date dateToday = new Date();
        allactivitiesList.forEach(activity -> {
            if (activity.getEndTime().before(dateToday)) {
                activitiesList.add(activity);
            }
        });
        List<SignUpNote> notesList = activitySignUpService.getNotes(() -> {
            SignUpNote note = new SignUpNote();
            note.setActivityId(Integer.parseInt(id));
            return note;
        });
        for (SignUpNote note : notesList) {
            volunteersList.add((Volunteer)volunteerService.getUser(note.getVolunteerId()));
            checkOutStatusList.add(note.getCheckOutFlag() == 1 ? "已签到" : "未签到");
            notesIdList.add(note.getId());
            notesGradeList.add(note.getScore() == null ? -1 : note.getScore());
        }
        modelAndView.addObject("selectedActivityId", id);
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("userList", volunteersList);
        modelAndView.addObject("notesCheckOutStatusList", checkOutStatusList);
        modelAndView.addObject("notesIdList", notesIdList);
        modelAndView.addObject("notesGradeList", notesGradeList);
        return modelAndView;
    }

    @GetMapping(value = "/leader/activity_checkout/{id}")
    public String CheckOutActivityByLeader(@PathVariable(value = "id") String id, ModelAndView modelAndView) {
        boolean flag = activitySignUpService.checkOutActivity(id);
        if (flag) {
            return "redirect:/leader/message/checkout_success";
        } else {
            return "redirect:/leader/warning/checkout_failed";
        }
    }

    @GetMapping(value = "/leader/activity_kick_out/{id}")
    public String kickOutActivity(@PathVariable(value = "id") String id, ModelAndView modelAndView) {
        boolean flag = activitySignUpService.exitActivity(id);
        if (flag) {
            return "redirect:/leader/message/kick_out_success";
        } else {
            return "redirect:/leader/warning/kick_out_failed";
        }
    }

    @RequestMapping(value = "/leader/activity_score", method = RequestMethod.POST)
    public String ScoreActivity(@RequestParam(value = "note_id") String id, @RequestParam(value = "score") String score, ModelAndView modelAndView) {
        boolean flag = activityScoreService.score(() -> {
            SignUpNote note = new SignUpNote();
            note.setId(Integer.parseInt(id));
            note.setScore(Integer.parseInt(score));
            return note;
        });
        if (flag) {
            return "redirect:/leader/message/activity_score_success";
        } else {
            return "redirect:/leader/warning/activity_score_failed";
        }
    }

}
